#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#import os
#import sys
#import math
#ROOT = os.path.dirname(os.path.abspath(__file__))
#sys.path.insert(0, os.path.join(ROOT, '..'))

import logging
import string
from pygooglechart import Chart
from pygooglechart import SparkLineChart

from django.utils import simplejson as json
import datetime
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

#import settings
#import helper

class BleedingData(db.Model):
    #TODO: figure out the parameters to pass to the properties
    patient_firstname   = db.StringProperty(required=False)
    patient_lastname    = db.StringProperty(required=False)
    patient_age         = db.IntegerProperty(required=False)
    patient_gender      = db.IntegerProperty(required=False)
    date                = db.DateTimeProperty(auto_now_add=False)
    risk_scale          = db.IntegerProperty(required=False)
    #risk_timi          = []
    risk_timi           = db.ListProperty(int, default=[])
    #risk_gusto         = []
    risk_gusto          = db.ListProperty(int, default=[])
    #risk_pursuit       = []
    risk_pursuit        = db.ListProperty(int, default=[])
    #risk_predict       = []
    risk_predict        = db.ListProperty(int, default=[])
    #risk_barc          = []
    risk_barc           = db.ListProperty(int, default=[])
    
    #cadillac -- enter values for each category and the sum in the score
    risk_cadillac_lvef  = db.IntegerProperty(required=False)
    risk_cadillac_renal = db.IntegerProperty(required=False)
    risk_cadillac_killip= db.IntegerProperty(required=False)
    risk_cadillac_timi  = db.IntegerProperty(required=False)
    risk_cadillac_age   = db.IntegerProperty(required=False)
    risk_cadillac_anemia= db.IntegerProperty(required=False)
    risk_cadillac_vessel= db.IntegerProperty(required=False)
    risk_cadillac_score = db.IntegerProperty(required=False)
    
    #acuity--enter values for each category and the cummulative in the score
    risk_acuity_gender  = db.IntegerProperty(required=False)
    risk_acuity_age     = db.IntegerProperty(required=False)
    risk_acuity_serum   = db.IntegerProperty(required=False)
    risk_acuity_anemia  = db.IntegerProperty(required=False)
    risk_acuity_stemi   = db.IntegerProperty(required=False)
    risk_acuity_drug    = db.IntegerProperty(required=False)
    risk_acuity_score   = db.IntegerProperty(required=False)
    
    #timi				= [pdm, sbp, hr, killip, weight, anterior, tot]
    risk_timi_pdm		= db.IntegerProperty(required=False)
    risk_timi_sbp		= db.IntegerProperty(required=False)
    risk_timi_hr		= db.IntegerProperty(required=False)
    risk_timi_killip	= db.IntegerProperty(required=False)
    risk_timi_weight	= db.IntegerProperty(required=False)
    risk_timi_anterior	= db.IntegerProperty(required=False)
    risk_timi_tot		= db.IntegerProperty(required=False)
    
    #procedure_data     = [site, attempts, closure device, baseline coagulation, ACT, HIT] 
    procedure_site      = db.IntegerProperty(required=False)
    procedure_attempts  = db.IntegerProperty(required=False)
    procedure_closure   = db.IntegerProperty(required=False)
    procedure_coag      = db.IntegerProperty(required=False)
    procedure_act       = db.IntegerProperty(required=False)
    procedure_hit       = db.IntegerProperty(required=False)
    
    #drugs_data         = [heparin, asprin, bivalirudin, 2b3a inhibitors, adp inhibitors]
    drugs_heparin       = db.IntegerProperty(required=False)
    drugs_asprin        = db.IntegerProperty(required=False)
    drugs_bival         = db.IntegerProperty(required=False)
    drugs_2b3a          = db.IntegerProperty(required=False)
    drugs_adp           = db.IntegerProperty(required=False)
    
    #bleeding stuff
    bleeding_scale      = db.IntegerProperty(required=False)
    #bleeding_timi      = []
    bleeding_timi       = db.ListProperty(int, default=[])
    #bleeding_gusto     = []
    bleeding_gusto      = db.ListProperty(int, default=[])
    #dictionary          = dict((name, eval(name)) for name in list_of_variable_names)
    ##def getDictionary(self):
    #    return self.__dict__

class MainHandler(webapp.RequestHandler):
    def sparklines(self):
        #print 'blah'
        chart = SparkLineChart(100, 100)
        
        chart.add_data([1,2,4,8,7,6])
        #print chart.get_url()
        #aa = open("ads.png","w")
        #aa.close()
        #chart.download('line-sparkline.png')
    def get(self):
        self.response.out.write('<a href="/patients">Patients</a><br/><a href="/outcomes">Outcomes</a><br/>')
        self.sparklines()
        self.response.out.write('<form method="post"><input value="Install" type="submit"/></form>')

    #this is for getting a list of all entries in the db. alternetively, use the getEntry function with
    #an empty dictionary
    def getTable(self):
        entities = BleedingData.all()
        #make json
        return createJsonStr(entities)
        
    #convert a list of entities into json format
    def createJsonStr(self, entities):
        list_dictionary = []
        for entity in entities:
            list_dictionary.append(entity.__dict__) 
        return json.dumps(list_dictionary)    

    #this is used for filtering.
    #dictionary is just a key-value pair that we want to filter against
    #only pairs that we care should be in there, the rest are considered wildcards.
    #dictionary keys should *not* be firstname, lastname, or date (these won't work for now)
    #keys should have the same names as the db fields
    #all values are integer and should reflect the associated scores. e.g., if in cadillac we want to
    #filter against age>65, we should have dictionary['risk_cadillac_age'] = 2
    def getEntity(self, dictionary):
        #how to filter???
        query = 'SELECT * FROM Greeting WHERE 1 = 1'
        append = ' AND '
        for key in dictionary.keys():
            #key = mykey[1:] #take the first underscore out
            query = query + append
            query = query + str(key) + ' = ' + str(dictionary[key])
        results = db.GqlQuery(query)
        return createJsonStr(entities)
            
    #a half-assed post. this assumes that it receives a record and pushes it into the db
    #this assumes that all fields of the entity are given in the post arguments (the unrelated
    #fields should have a value of -1). *** if you want to only return the relevant fields, thats cool.
    #just let me know and i can adjust this
    #it returns a json copy of the record
    def post(self):
        #self.response.out.write('shit starting')
        entity = BleedingData()
        #TODO: update the fields of entity from the post data
        #entity.risk_scale = self.request.get('blah')
        print 'holla'
        arguments = self.request.arguments()
        dictionary = entity.__dict__
        #entity.firstname = 'aaa'
        #print arguments
        print 'end'
        #print entity.__dict__['firstname']
        #for argument in arguments:
        #    dictionary[argument] = self.request.get(argument)
        #entity.put()
        
        #self.response.out.write('({ Status: "Success", "Message": "Patient Added Successfully." })')
        #return json.dumps(entity.getDictionary())
        
        

class SaveHandler(webapp.RequestHandler):
    def sparklines(self):
        #print 'blah'
        chart = SparkLineChart(100, 100)
        
        chart.add_data([1,2,4,8,7,6])
        #print chart.get_url()
        #aa = open("ads.png","w")
        #aa.close()
        #chart.download('line-sparkline.png')
    #def get(self):
    #    self.response.out.write('<a href="/patients">Patients</a><br/><a href="/outcomes">Outcomes</a><br/>')
    #    self.sparklines()
    #    self.response.out.write('<form method="post"><input value="Install" type="submit"/></form>')

    #this is for getting a list of all entries in the db. alternetively, use the getEntry function with
    #an empty dictionary
    def getTable(self):
        entities = BleedingData.all()
        #make json
        return createJsonStr(entities)
        
    #convert a list of entities into json format
    def createJsonStr(self, entities):
        list_dictionary = []
        for entity in entities:
            list_dictionary.append(entity.__dict__) 
        return json.dumps(list_dictionary)    

    #this is used for filtering.
    #dictionary is just a key-value pair that we want to filter against
    #only pairs that we care should be in there, the rest are considered wildcards.
    #dictionary keys should *not* be firstname, lastname, or date (these won't work for now)
    #keys should have the same names as the db fields
    #all values are integer and should reflect the associated scores. e.g., if in cadillac we want to
    #filter against age>65, we should have dictionary['risk_cadillac_age'] = 2
    def getEntity(self, dictionary):
        #how to filter???
        query = 'SELECT * FROM Greeting WHERE 1 = 1'
        append = ' AND '
        for key in dictionary.keys():
            #key = mykey[1:] #take the first underscore out
            query = query + append
            query = query + str(key) + ' = ' + str(dictionary[key])
        results = db.GqlQuery(query)
        return createJsonStr(entities)
            
    #a half-assed post. this assumes that it receives a record and pushes it into the db
    #this assumes that all fields of the entity are given in the post arguments (the unrelated
    #fields should have a value of -1). *** if you want to only return the relevant fields, thats cool.
    #just let me know and i can adjust this
    #it returns a json copy of the record
    def post(self):
        #self.response.out.write('shit starting')
        entity = BleedingData()
        #TODO: update the fields of entity from the post data
        #entity.risk_scale = self.request.get('blah')
        arguments = self.request.arguments()
        #dictionary = entity.__dict__
        #entity.firstname = 'aaa'
        #self.response.out.write(arguments)
        #print entity.__dict__['firstname']
        for argument in arguments:
            if (argument[0:len('patient-')] == 'patient-'):
                db_arg = ''
                db_arg += string.replace(argument, '-', '_')
                db_val = self.request.get(argument)
                
                
                #dictionary[db_arg] = db_val
                #TODO(sanjeev): stop exposing ourselves to xss!!!!
                if(hasattr(entity, db_arg)):
                    if(db_val == 'true'):
                        db_val = 1
                    elif(db_val == 'false'):
                        db_val = 0
                    try:
                      setattr(entity, db_arg, db_val)
                    except:
                      setattr(entity, db_arg, int(db_val))
                    logging.error('--- '+ str(getattr(entity, db_arg)))
                
                logging.error('putting '+ self.request.get(argument) + ' in db at arg '+ db_arg)
            elif (((argument[0:len('timi-')] == 'timi-') |
                (argument[0:len('gusto-')] == 'gusto-') |
                (argument[0:len('predict-')] == 'predict-') |
                (argument[0:len('pursuit-')] == 'pursuit-') |
                (argument[0:len('acuity-')] == 'acuity-') |
                (argument[0:len('cadillac-')] == 'cadillac-')) &
                (argument != 'timi-0')):
                db_arg = 'risk_'
                db_arg += string.replace(argument, '-', '_')
                db_val = self.request.get(argument)
                
                if(db_val == 'true'):
                    db_val = 1
                elif(db_val == 'false'):
                    db_val = 0
                
                #dictionary[db_arg] = db_val
                #TODO(sanjeev): stop exposing ourselves to xss!!!!
                
                #eval("entity.%s = db_val" % (db_arg))
                if(hasattr(entity, db_arg)):
                    setattr(entity, db_arg, db_val)
                    logging.error('--- '+ str(getattr(entity, db_arg)))
                #logging.error('putting '+ str(db_val) + ' in db at arg '+ db_arg)
                logging.error('putting '+ str(db_val) + ' in db at arg '+ db_arg)
            else:
                pass
                #logging.error('---'+argument)
            #dictionary[argument] = self.request.get(argument)
        entity.put()
        #entity1 = BleedingData()
        #entity1.patient_firstname = 'hola'
        #entity1.put()
        logging.error('entry1 added')
        logging.error('entry added')
        
        #self.response.out.write('({ Status: "Success", "Message": "Patient Added Successfully." })')
        #return json.dumps(entity.getDictionary())
        
class ListUsersHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
               providers: [{
               id: %i,
               title: '%s',
               department: '%s',
               region: '%s',
               facility: '%s',
               thumbnail: '/providers/%s.jpeg'
           }]""" % 
           ())

class ProviderData(db.Model):
    user_id             = db.IntegerProperty(required=False)
    share_my_data       = db.BooleanProperty(required=True, default=True)
    users_followed      = db.ListProperty(int, required=True, default=[])
    title               = db.StringProperty(required=True)
    department          = db.StringProperty(required=False)
    region              = db.StringProperty(required=False)
    facility            = db.StringProperty(required=False)
    thumnail            = db.StringProperty(required=False)

def main():
    #provider = ProviderData()
    #provider.user_id = 1
    #provider.share_my_data = True
    #provider.users_followed = [1, 2, 3]
    #provider.title = 'Dr. Nicholas'
    #provider.department = 'Cardiology'
    #provider.region = 'CA'
    #provider.facility = 'UCLA'
    #provider.thumnail = '1.jpeg'    
    #provider.put()
    application = webapp.WSGIApplication([('/', MainHandler), ('/save', SaveHandler)],
                                         debug=False)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
